<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="xcode," />





  <link rel="alternate" href="/atom.xml" title="搁浅丶岁月的变迁" type="application/atom+xml" />






<meta name="description" content="前言 在上篇文章中介绍了ReactiveCocoa的基础知识,接下来我们来深入介绍ReactiveCocoa及其在MVVM中的用法。   常见操作方法介绍操作须知所有的信号（RACSignal）都可以进行操作处理，因为所有操作方法都定义在RACStream.h中，因此只要继承RACStream就有了操作处理方法。 操作思想运用的是Hook（钩子）思想，Hook是一种用于改变API(应用程序编程接口">
<meta name="keywords" content="xcode">
<meta property="og:type" content="article">
<meta property="og:title" content="ReactiveCocoa 进阶">
<meta property="og:url" content="http://yoursite.com/2017/01/06/2016-01-06-ReactiveCocoa-进阶/index.html">
<meta property="og:site_name" content="搁浅丶岁月的变迁">
<meta property="og:description" content="前言 在上篇文章中介绍了ReactiveCocoa的基础知识,接下来我们来深入介绍ReactiveCocoa及其在MVVM中的用法。   常见操作方法介绍操作须知所有的信号（RACSignal）都可以进行操作处理，因为所有操作方法都定义在RACStream.h中，因此只要继承RACStream就有了操作处理方法。 操作思想运用的是Hook（钩子）思想，Hook是一种用于改变API(应用程序编程接口">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://ww3.sinaimg.cn/large/006y8lVagw1fbgye3re5xj30je0iomz8.jpg">
<meta property="og:image" content="https://ww2.sinaimg.cn/large/006y8lVagw1fbdf6cyez6j30id0kkabf.jpg">
<meta property="og:image" content="https://ww3.sinaimg.cn/large/006y8lVagw1fbgvoh8yu6j30bj0l43yz.jpg">
<meta property="og:updated_time" content="2018-03-08T07:33:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ReactiveCocoa 进阶">
<meta name="twitter:description" content="前言 在上篇文章中介绍了ReactiveCocoa的基础知识,接下来我们来深入介绍ReactiveCocoa及其在MVVM中的用法。   常见操作方法介绍操作须知所有的信号（RACSignal）都可以进行操作处理，因为所有操作方法都定义在RACStream.h中，因此只要继承RACStream就有了操作处理方法。 操作思想运用的是Hook（钩子）思想，Hook是一种用于改变API(应用程序编程接口">
<meta name="twitter:image" content="https://ww3.sinaimg.cn/large/006y8lVagw1fbgye3re5xj30je0iomz8.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/01/06/2016-01-06-ReactiveCocoa-进阶/"/>





  <title>ReactiveCocoa 进阶 | 搁浅丶岁月的变迁</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/liaoren512"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_red_aa0000.png" alt="Fork me on GitHub"></a>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">搁浅丶岁月的变迁</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">没有虽败犹荣，只有成王败寇。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/01/06/2016-01-06-ReactiveCocoa-进阶/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="廖壬">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/ichgo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="搁浅丶岁月的变迁">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ReactiveCocoa 进阶</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-01-06T00:00:00+08:00">
                2017-01-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><blockquote>
<p>在<a href="http://qiubaiying.github.io/2016/12/26/ReactiveCocoa-基础/" target="_blank" rel="noopener">上篇文章</a>中介绍了<strong>ReactiveCocoa</strong>的基础知识,接下来我们来深入介绍<strong>ReactiveCocoa</strong>及其在<strong>MVVM</strong>中的用法。</p>
</blockquote>
<p><img src="https://ww3.sinaimg.cn/large/006y8lVagw1fbgye3re5xj30je0iomz8.jpg" alt="ReactiveCocoa进阶思维导图"></p>
<h1 id="常见操作方法介绍"><a href="#常见操作方法介绍" class="headerlink" title="常见操作方法介绍"></a>常见操作方法介绍</h1><h4 id="操作须知"><a href="#操作须知" class="headerlink" title="操作须知"></a>操作须知</h4><p>所有的信号（RACSignal）都可以进行操作处理，因为所有操作方法都定义在RACStream.h中，因此只要继承RACStream就有了操作处理方法。</p>
<h4 id="操作思想"><a href="#操作思想" class="headerlink" title="操作思想"></a>操作思想</h4><p>运用的是Hook（钩子）思想，Hook是一种用于改变API(应用程序编程接口：方法)执行结果的技术.</p>
<p>Hook用处：截获API调用的技术。</p>
<p>有关Hook的知识可以看我的这篇博客<a href="http://www.jianshu.com/p/ff114e69cc0a" target="_blank" rel="noopener">《Objective-C Runtime 的一些基本使用》</a>中的 <em>更换代码的实现方法</em> 一节,</p>
<p>Hook原理：在每次调用一个API返回结果之前，先执行你自己的方法，改变结果的输出。</p>
<h4 id="操作方法"><a href="#操作方法" class="headerlink" title="操作方法"></a>操作方法</h4><h4 id="bind（绑定）-ReactiveCocoa核心方法"><a href="#bind（绑定）-ReactiveCocoa核心方法" class="headerlink" title="bind（绑定）- ReactiveCocoa核心方法"></a><strong>bind</strong>（绑定）- ReactiveCocoa核心方法</h4><p><strong>ReactiveCocoa</strong> 操作的核心方法是 <strong>bind</strong>（绑定）,而且也是RAC中核心开发方式。之前的开发方式是赋值，而用RAC开发，应该把重心放在绑定，也就是可以在创建一个对象的时候，就绑定好以后想要做的事情，而不是等赋值之后在去做事情。</p>
<p>列如，把数据展示到控件上，之前都是重写控件的 <code>setModel</code> 方法，用RAC就可以在一开始创建控件的时候，就绑定好数据。</p>
<ul>
<li><p><strong>作用</strong></p>
<p>  RAC底层都是调用<strong>bind</strong>， 在开发中很少直接使用 <strong>bind</strong> 方法，<strong>bind</strong>属于RAC中的底层方法，我们只需要调用封装好的方法，<strong>bind</strong>用作了解即可.</p>
</li>
<li><p><strong>bind方法使用步骤</strong></p>
<ol>
<li>传入一个返回值 <code>RACStreamBindBlock</code> 的 block。</li>
<li>描述一个 <code>RACStreamBindBlock</code> 类型的 <code>bindBlock</code>作为block的返回值。</li>
<li><p>描述一个返回结果的信号，作为 <code>bindBlock</code> 的返回值。</p>
<p>注意：在bindBlock中做信号结果的处理。</p>
</li>
</ol>
</li>
<li><p><strong>bind方法参数</strong></p>
<p><strong>RACStreamBindBlock</strong>:<br><code>typedef RACStream * (^RACStreamBindBlock)(id value, BOOL *stop);</code></p>
<p><code>参数一(value)</code>:表示接收到信号的原始值，还没做处理</p>
<p><code>参数二(*stop)</code>:用来控制绑定Block，如果*stop = yes,那么就会结束绑定。</p>
<p><code>返回值</code>：信号，做好处理，在通过这个信号返回出去，一般使用 <code>RACReturnSignal</code>,需要手动导入头文件<code>RACReturnSignal.h</code></p>
</li>
<li><p><strong>使用</strong></p>
<p>  假设想监听文本框的内容，并且在每次输出结果的时候，都在文本框的内容拼接一段文字“输出：”</p>
<ul>
<li><p>使用封装好的方法：在返回结果后，拼接。</p>
  <figure class="highlight hy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[_textField.rac_textSignal subscribeNext:^(<span class="name"><span class="builtin-name">id</span></span> x) &#123;</span><br><span class="line"></span><br><span class="line">	// 在返回结果后，拼接 输出：</span><br><span class="line">	NSLog(@<span class="string">"输出:%@"</span>,x)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">&#125;]<span class="comment">;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>方式二:，使用RAC中 <code>bind</code> 方法做处理，在返回结果前，拼接。</p>
<p>  这里需要手动导入<code>#import &lt;ReactiveCocoa/RACReturnSignal.h&gt;</code>，才能使用<code>RACReturnSignal</code></p>
  <figure class="highlight hy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">[[_textField.rac_textSignal bind:<span class="comment">^RACStreamBindBlock</span>&#123;</span><br><span class="line">   // 什么时候调用:</span><br><span class="line">   // block作用:表示绑定了一个信号.</span><br><span class="line"></span><br><span class="line">   return <span class="comment">^RACStream</span> *(<span class="name"><span class="builtin-name">id</span></span> value, BOOL *stop)&#123;</span><br><span class="line"></span><br><span class="line">       // 什么时候调用block:当信号有新的值发出，就会来到这个block。</span><br><span class="line"></span><br><span class="line">       // block作用:做返回值的处理</span><br><span class="line"></span><br><span class="line">       // 做好处理，在返回结果前，拼接 输出:</span><br><span class="line">       return [RACReturnSignal return:[NSString stringWithFormat:@<span class="string">"输出:%@"</span>,value]]<span class="comment">;</span></span><br><span class="line">   &#125;<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">&#125;] subscribeNext:^(<span class="name"><span class="builtin-name">id</span></span> x) &#123;</span><br><span class="line"></span><br><span class="line">   NSLog(@<span class="string">"%@"</span>,x)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">&#125;]<span class="comment">;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p><strong>底层实现</strong></p>
<ol>
<li>源信号调用bind,会重新创建一个绑定信号。</li>
<li>当绑定信号被订阅，就会调用绑定信号中的 <code>didSubscribe</code> ，生成一个 <code>bindingBlock</code> 。</li>
<li>当源信号有内容发出，就会把内容传递到 <code>bindingBlock</code> 处理，调用<code>bindingBlock(value,stop)</code></li>
<li>调用<code>bindingBlock(value,stop)</code>，会返回一个内容处理完成的信号<code>RACReturnSignal</code>。</li>
<li><p>订阅<code>RACReturnSignal</code>，就会拿到绑定信号的订阅者，把处理完成的信号内容发送出来。</p>
<p>注意:不同订阅者，保存不同的nextBlock，看源码的时候，一定要看清楚订阅者是哪个。</p>
</li>
</ol>
</li>
</ul>
<h4 id="映射"><a href="#映射" class="headerlink" title="映射"></a>映射</h4><p>映射主要用这两个方法实现：<strong>flattenMap</strong>,<strong>Map</strong>,用于把源信号内容映射成新的内容。</p>
<h6 id="flattenMap"><a href="#flattenMap" class="headerlink" title="flattenMap"></a>flattenMap</h6><ul>
<li><p><strong>作用</strong></p>
<p>  把源信号的内容映射成一个新的信号，信号可以是任意类型</p>
</li>
<li><p><strong>使用步骤</strong></p>
<ol>
<li>传入一个block，block类型是返回值<code>RACStream</code>，参数value</li>
<li>参数value就是源信号的内容，拿到源信号的内容做处理</li>
<li>包装成<code>RACReturnSignal</code>信号，返回出去。</li>
</ol>
</li>
</ul>
<ul>
<li><p><strong>使用</strong></p>
<p>  监听文本框的内容改变，把结构重新映射成一个新值.</p>
  <figure class="highlight hy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">[[_textField.rac_textSignal flattenMap:<span class="comment">^RACStream</span> *(<span class="name"><span class="builtin-name">id</span></span> value) &#123;</span><br><span class="line">       </span><br><span class="line">       // block调用时机：信号源发出的时候</span><br><span class="line">       </span><br><span class="line">       // block作用：改变信号的内容</span><br><span class="line">       </span><br><span class="line">       // 返回RACReturnSignal</span><br><span class="line">       return [RACReturnSignal return:[NSString stringWithFormat:@<span class="string">"信号内容：%@"</span>, value]]<span class="comment">;</span></span><br><span class="line">       </span><br><span class="line">   &#125;] subscribeNext:^(<span class="name"><span class="builtin-name">id</span></span> x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"%@"</span>, x)<span class="comment">;</span></span><br><span class="line">   &#125;]<span class="comment">;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>底层实现</strong></p>
<ol start="0">
<li><strong>flattenMap</strong>内部调用 <code>bind</code> 方法实现的,<strong>flattenMap</strong>中block的返回值，会作为bind中bindBlock的返回值。</li>
<li>当订阅绑定信号，就会生成 <code>bindBlock</code>。</li>
<li>当源信号发送内容，就会调用<code>bindBlock(value, *stop)</code></li>
<li>调用<code>bindBlock</code>，内部就会调用 <strong>flattenMap</strong> 的 bloc k，<strong>flattenMap</strong> 的block作用：就是把处理好的数据包装成信号。</li>
<li>返回的信号最终会作为 <code>bindBlock</code> 中的返回信号，当做 <code>bindBlock</code> 的返回信号。</li>
<li>订阅 <code>bindBlock</code> 的返回信号，就会拿到绑定信号的订阅者，把处理完成的信号内容发送出来。</li>
</ol>
</li>
</ul>
<h6 id="Map"><a href="#Map" class="headerlink" title="Map"></a>Map</h6><ul>
<li><p><strong>作用</strong></p>
<p>  把源信号的值映射成一个新的值</p>
</li>
</ul>
<ul>
<li><p><strong>使用步骤</strong></p>
<ol>
<li>传入一个block,类型是返回对象，参数是 <code>value</code></li>
<li><code>value</code>就是源信号的内容，直接拿到源信号的内容做处理</li>
<li>把处理好的内容，直接返回就好了，不用包装成信号，返回的值，就是映射的值。</li>
</ol>
</li>
<li><p><strong>使用</strong></p>
<p>  监听文本框的内容改变，把结构重新映射成一个新值.</p>
  <figure class="highlight hy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">[[_textField.rac_textSignal map:<span class="comment">^id</span>(<span class="name"><span class="builtin-name">id</span></span> value) &#123;</span><br><span class="line">      </span><br><span class="line">      // 拼接完后，返回对象</span><br><span class="line">       return [NSString stringWithFormat:@<span class="string">"信号内容: %@"</span>, value]<span class="comment">;</span></span><br><span class="line">       </span><br><span class="line">   &#125;] subscribeNext:^(<span class="name"><span class="builtin-name">id</span></span> x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"%@"</span>, x)<span class="comment">;</span></span><br><span class="line">   &#125;]<span class="comment">;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>底层实现</strong>:</p>
<ol start="0">
<li>Map底层其实是调用 <code>flatternMa</code>p,<code>Map</code> 中block中的返回的值会作为 <code>flatternMap</code> 中block中的值</li>
<li>当订阅绑定信号，就会生成 <code>bindBlock</code> </li>
<li>当源信号发送内容，就会调用 <code>bindBlock(value, *stop)</code></li>
<li>调用 <code>bindBlock</code> ，内部就会调用 <code>flattenMap的block</code></li>
<li><code>flattenMap的block</code> 内部会调用 <code>Map</code> 中的block，把 <code>Map</code> 中的block返回的内容包装成返回的信号</li>
<li>返回的信号最终会作为 <code>bindBlock</code> 中的返回信号，当做 <code>bindBlock</code> 的返回信号</li>
<li>订阅 <code>bindBlock</code> 的返回信号，就会拿到绑定信号的订阅者，把处理完成的信号内容发送出来。</li>
</ol>
</li>
</ul>
<h6 id="FlatternMap-和-Map-的区别"><a href="#FlatternMap-和-Map-的区别" class="headerlink" title="FlatternMap 和 Map 的区别"></a>FlatternMap 和 Map 的区别</h6><ul>
<li><strong>FlatternMap</strong> 中的Block <strong>返回信号</strong>。 </li>
</ul>
<ol start="2">
<li><strong>Map</strong> 中的Block <strong>返回对象</strong>。</li>
<li>开发中，如果信号发出的值 <strong>不是信号</strong> ，映射一般使用 <code>Map</code></li>
<li>如果信号发出的值 <strong>是信号</strong>，映射一般使用 <code>FlatternMap</code>。</li>
</ol>
<ul>
<li><p><code>signalOfsignals</code>用 <strong>FlatternMap</strong></p>
  <figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建信号中的信号</span></span><br><span class="line">RACSubject *signalOfsignals = [RACSubject subject];</span><br><span class="line">RACSubject *signal = [RACSubject subject];</span><br><span class="line"></span><br><span class="line">[[signalOfsignals <span class="string">flattenMap:</span>^RACStream *(id value) &#123;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 当signalOfsignals的signals发出信号才会调用</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> value;</span><br><span class="line"></span><br><span class="line">&#125;] <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 只有signalOfsignals的signal发出信号才会调用，因为内部订阅了bindBlock中返回的信号，也就是flattenMap返回的信号。</span></span><br><span class="line">    <span class="comment">// 也就是flattenMap返回的信号发出内容，才会调用。</span></span><br><span class="line"></span><br><span class="line">    NSLog(@<span class="string">"signalOfsignals：%@"</span>,x);</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 信号的信号发送信号</span></span><br><span class="line">[signalOfsignals <span class="string">sendNext:</span>signal];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 信号发送内容</span></span><br><span class="line">[signal <span class="string">sendNext:</span>@<span class="string">"hi"</span>];</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="组合"><a href="#组合" class="headerlink" title="组合"></a>组合</h4><p>组合就是将多个信号按照某种规则进行拼接，合成新的信号。</p>
<h6 id="concat"><a href="#concat" class="headerlink" title="concat"></a>concat</h6><ul>
<li><p><strong>作用</strong> </p>
<p>  按<strong>顺序拼接</strong>信号，当多个信号发出的时候，有顺序的接收信号。</p>
</li>
<li><strong>底层实现</strong><ol>
<li>当拼接信号被订阅，就会调用拼接信号的didSubscribe</li>
<li>didSubscribe中，会先订阅第一个源信号（signalA）</li>
<li>会执行第一个源信号（signalA）的didSubscribe</li>
<li>第一个源信号（signalA）didSubscribe中发送值，就会调用第一个源信号（signalA）订阅者的nextBlock,通过拼接信号的订阅者把值发送出来.</li>
<li>第一个源信号（signalA）didSubscribe中发送完成，就会调用第一个源信号（signalA）订阅者的completedBlock,订阅第二个源信号（signalB）这时候才激活（signalB）。</li>
<li>订阅第二个源信号（signalB）,执行第二个源信号（signalB）的didSubscribe</li>
<li>第二个源信号（signalA）didSubscribe中发送值,就会通过拼接信号的订阅者把值发送出来.</li>
</ol>
</li>
<li><p><strong>使用步骤</strong></p>
<ol>
<li>使用<code>concat:</code>拼接信号</li>
<li>订阅拼接信号，内部会自动按拼接顺序订阅信号</li>
</ol>
</li>
<li><p><strong>使用</strong></p>
<p>  拼接信号 <code>signalA</code>、 <code>signalB</code>、 <code>signalC</code></p>
  <figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">RACSignal *signalA = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"Hello"</span>];</span><br><span class="line">       </span><br><span class="line">       [subscriber sendCompleted];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   RACSignal *signalB = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"World"</span>];</span><br><span class="line">       </span><br><span class="line">       [subscriber sendCompleted];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   RACSignal *signalC = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"!"</span>];</span><br><span class="line">       </span><br><span class="line">       [subscriber sendCompleted];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 拼接 A B, 把signalA拼接到signalB后，signalA发送完成，signalB才会被激活。</span></span><br><span class="line">   RACSignal *concatSignalAB = [signalA <span class="string">concat:</span>signalB];</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// A B + C</span></span><br><span class="line">   RACSignal *concatSignalABC = [concatSignalAB <span class="string">concat:</span>signalC];</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 订阅拼接的信号, 内部会按顺序订阅 A-&gt;B-&gt;C</span></span><br><span class="line">   <span class="comment">// 注意：第一个信号必须发送完成，第二个信号才会被激活...</span></span><br><span class="line">   [concatSignalABC <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"%@"</span>, x);</span><br><span class="line">   &#125;];</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="then"><a href="#then" class="headerlink" title="then"></a>then</h6><ul>
<li><p><strong>作用</strong> </p>
<p>  用于连接两个信号，当第一个信号完成，才会连接then返回的信号。</p>
</li>
<li><p><strong>底层实现</strong></p>
<ol>
<li>先过滤掉之前的信号发出的值</li>
<li>使用concat连接then返回的信号</li>
</ol>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">[[[RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">   </span><br><span class="line">   [subscriber <span class="string">sendNext:</span>@<span class="number">1</span>];</span><br><span class="line">   </span><br><span class="line">   [subscriber sendCompleted];</span><br><span class="line">   </span><br><span class="line">   <span class="keyword">return</span> nil;</span><br><span class="line">   </span><br><span class="line"> &#125;] <span class="string">then:</span>^RACSignal *&#123;</span><br><span class="line">   </span><br><span class="line">   	<span class="keyword">return</span> [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="number">2</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line"> &#125;] <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 只能接收到第二个信号的值，也就是then返回信号的值</span></span><br><span class="line">   NSLog(@<span class="string">"%@"</span>, x);</span><br><span class="line">   </span><br><span class="line"> &#125;];</span><br><span class="line"> </span><br><span class="line"> <span class="comment">///</span></span><br><span class="line"> 输出：<span class="number">2</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>注意</strong></p>
<p>  注意使用<code>then</code>，之前信号的值会被忽略掉.</p>
</li>
</ul>
<h6 id="merge"><a href="#merge" class="headerlink" title="merge"></a>merge</h6><ul>
<li><p><strong>作用</strong> </p>
<p>  合并信号,任何一个信号发送数据，都能监听到.</p>
</li>
<li><p><strong>底层实现</strong></p>
<ol>
<li>合并信号被订阅的时候，就会遍历所有信号，并且发出这些信号。</li>
<li>每发出一个信号，这个信号就会被订阅</li>
<li>也就是合并信号一被订阅，就会订阅里面所有的信号。</li>
<li>只要有一个信号被发出就会被监听。</li>
</ol>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">RACSignal *signalA = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"A"</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line"></span><br><span class="line">   RACSignal *signalB = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B"</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 合并信号, 任何一个信号发送数据，都能监听到</span></span><br><span class="line">   RACSignal *mergeSianl = [signalA <span class="string">merge:</span>signalB];</span><br><span class="line"></span><br><span class="line">   [mergeSianl <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 输出</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">13</span>:<span class="number">29</span>:<span class="number">08.013</span> ReactiveCocoa进阶[<span class="number">3627</span>:<span class="number">718315</span>] A</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">13</span>:<span class="number">29</span>:<span class="number">08.014</span> ReactiveCocoa进阶[<span class="number">3627</span>:<span class="number">718315</span>] B</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="zip"><a href="#zip" class="headerlink" title="zip"></a>zip</h6><ul>
<li><p><strong>作用</strong> </p>
<p>  把两个信号压缩成一个信号，只有当两个信号 <strong>同时</strong> 发出信号内容时，并且把两个信号的内容合并成一个元组，才会触发压缩流的next事件。</p>
</li>
<li><p><strong>底层实现</strong></p>
<ol>
<li>定义压缩信号，内部就会自动订阅signalA，signalB</li>
<li>每当signalA或者signalB发出信号，就会判断signalA，signalB有没有发出个信号，有就会把每个信号 第一次 发出的值包装成元组发出</li>
</ol>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">RACSignal *signalA = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"A1"</span>];</span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"A2"</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   RACSignal *signalB = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B1"</span>];</span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B2"</span>];</span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B3"</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   RACSignal *zipSignal = [signalA <span class="string">zipWith:</span>signalB];</span><br><span class="line">   </span><br><span class="line">   [zipSignal <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">13</span>:<span class="number">48</span>:<span class="number">09.234</span> ReactiveCocoa进阶[<span class="number">3997</span>:<span class="number">789720</span>] <span class="string">zipWith:</span> &lt;<span class="string">RACTuple:</span> <span class="number">0x600000004df0</span>&gt; (</span><br><span class="line">   A1,</span><br><span class="line">   B1</span><br><span class="line">)</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">13</span>:<span class="number">48</span>:<span class="number">09.234</span> ReactiveCocoa进阶[<span class="number">3997</span>:<span class="number">789720</span>] <span class="string">zipWith:</span> &lt;<span class="string">RACTuple:</span> <span class="number">0x608000003410</span>&gt; (</span><br><span class="line">   A2,</span><br><span class="line">   B2</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="combineLatest"><a href="#combineLatest" class="headerlink" title="combineLatest"></a>combineLatest</h6><ul>
<li><p><strong>作用</strong> </p>
<p>  将多个信号合并起来，并且拿到各个信号最后一个值,必须每个合并的signal至少都有过一次sendNext，才会触发合并的信号。</p>
</li>
<li><p><strong>底层实现</strong></p>
<ol>
<li>当组合信号被订阅，内部会自动订阅signalA，signalB,必须两个信号都发出内容，才会被触发。</li>
<li>并且把两个信号的 最后一次 发送的值组合成元组发出。</li>
</ol>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">RACSignal *signalA = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"A1"</span>];</span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"A2"</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   RACSignal *signalB = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B1"</span>];</span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B2"</span>];</span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B3"</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   RACSignal *combineSianal = [signalA <span class="string">combineLatestWith:</span>signalB];</span><br><span class="line">   </span><br><span class="line">   [combineSianal <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"combineLatest:%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">13</span>:<span class="number">48</span>:<span class="number">09.235</span> ReactiveCocoa进阶[<span class="number">3997</span>:<span class="number">789720</span>] <span class="string">combineLatest:</span>&lt;<span class="string">RACTuple:</span> <span class="number">0x60800000e150</span>&gt; (</span><br><span class="line">   A2,</span><br><span class="line">   B1</span><br><span class="line">)</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">13</span>:<span class="number">48</span>:<span class="number">09.235</span> ReactiveCocoa进阶[<span class="number">3997</span>:<span class="number">789720</span>] <span class="string">combineLatest:</span>&lt;<span class="string">RACTuple:</span> <span class="number">0x600000004db0</span>&gt; (</span><br><span class="line">   A2,</span><br><span class="line">   B2</span><br><span class="line">)</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">13</span>:<span class="number">48</span>:<span class="number">09.236</span> ReactiveCocoa进阶[<span class="number">3997</span>:<span class="number">789720</span>] <span class="string">combineLatest:</span>&lt;<span class="string">RACTuple:</span> <span class="number">0x60800000e180</span>&gt; (</span><br><span class="line">   A2,</span><br><span class="line">   B3</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ul>
<li><p><strong>注意</strong></p>
<p>  <strong>combineLatest</strong>与<strong>zip</strong>用法相似，必须每个合并的signal至少都有过一次sendNext，才会触发合并的信号。</p>
<p>  区别看下图：</p>
<p>  <img src="https://ww2.sinaimg.cn/large/006y8lVagw1fbdf6cyez6j30id0kkabf.jpg" alt=""></p>
</li>
</ul>
<h6 id="reduce"><a href="#reduce" class="headerlink" title="reduce"></a>reduce</h6><ul>
<li><p><strong>作用</strong> </p>
<p>  把信号发出元组的值聚合成一个值</p>
</li>
<li><p><strong>底层实现</strong></p>
<ol>
<li>订阅聚合信号，</li>
<li>每次有内容发出，就会执行reduceblcok，把信号内容转换成reduceblcok返回的值。</li>
</ol>
</li>
<li><p><strong>使用</strong></p>
<p>   常见的用法，（先组合在聚合）<code>combineLatest:(id&lt;NSFastEnumeration&gt;)signals reduce:(id (^)())reduceBlock</code></p>
<p>   reduce中的block简介:</p>
<p>   reduceblcok中的参数，有多少信号组合，reduceblcok就有多少参数，每个参数就是之前信号发出的内容<br>   reduceblcok的返回值：聚合信号之后的内容。</p>
</li>
</ul>
<pre><code><figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">    RACSignal *signalA = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"A1"</span>];</span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"A2"</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   RACSignal *signalB = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B1"</span>];</span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B2"</span>];</span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"B3"</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">   RACSignal *reduceSignal = [RACSignal <span class="string">combineLatest:</span>@[signalA, signalB] <span class="string">reduce:</span>^id(NSString *str1, NSString *str2)&#123;</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> [NSString <span class="string">stringWithFormat:</span>@<span class="string">"%@ %@"</span>, str1, str2];</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   [reduceSignal <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 输出</span></span><br><span class="line">   <span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">15</span>:<span class="number">42</span>:<span class="number">41.803</span> ReactiveCocoa进阶[<span class="number">4248</span>:<span class="number">1264674</span>] A2 B1</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">15</span>:<span class="number">42</span>:<span class="number">41.803</span> ReactiveCocoa进阶[<span class="number">4248</span>:<span class="number">1264674</span>] A2 B2</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">15</span>:<span class="number">42</span>:<span class="number">41.803</span> ReactiveCocoa进阶[<span class="number">4248</span>:<span class="number">1264674</span>] A2 B3</span><br></pre></td></tr></table></figure>
</code></pre><h4 id="过滤"><a href="#过滤" class="headerlink" title="过滤"></a>过滤</h4><p>过滤就是过滤信号中的 特定值 ，或者过滤指定 发送次数 的信号。</p>
<h6 id="filter"><a href="#filter" class="headerlink" title="filter"></a>filter</h6><ul>
<li><p><strong>作用</strong></p>
<p>  过滤信号，使用它可以获取满足条件的信号.</p>
<p>  block的返回值是Bool值，返回<code>NO</code>则过滤该信号</p>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 过滤:</span></span><br><span class="line"><span class="comment">// 每次信号发出，会先执行过滤条件判断.</span></span><br><span class="line"><span class="selector-attr">[[_textField.rac_textSignal filter:^BOOL(NSString *value) &#123;</span></span><br><span class="line"><span class="selector-attr">       </span></span><br><span class="line"><span class="selector-attr">       NSLog(@"原信号: %@", value);</span></span><br><span class="line"><span class="selector-attr"></span></span><br><span class="line"><span class="selector-attr">       // 过滤 长度 &lt;= 3 的信号</span></span><br><span class="line"><span class="selector-attr">       return value.length &gt; 3;</span></span><br><span class="line"><span class="selector-attr">       </span></span><br><span class="line"><span class="selector-attr">   &#125;]</span> <span class="selector-tag">subscribeNext</span>:^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       <span class="selector-tag">NSLog</span>(@<span class="string">"长度大于3的信号：%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 在_textField中输出12345</span></span><br><span class="line"><span class="comment">// 输出</span></span><br><span class="line"><span class="selector-tag">2017-01-03</span> <span class="selector-tag">16</span><span class="selector-pseudo">:36</span><span class="selector-pseudo">:54.938</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[4714:1552910]</span> 原信号: <span class="selector-tag">1</span></span><br><span class="line"><span class="selector-tag">2017-01-03</span> <span class="selector-tag">16</span><span class="selector-pseudo">:36</span><span class="selector-pseudo">:55.383</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[4714:1552910]</span> 原信号: <span class="selector-tag">12</span></span><br><span class="line"><span class="selector-tag">2017-01-03</span> <span class="selector-tag">16</span><span class="selector-pseudo">:36</span><span class="selector-pseudo">:55.706</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[4714:1552910]</span> 原信号: <span class="selector-tag">123</span></span><br><span class="line"><span class="selector-tag">2017-01-03</span> <span class="selector-tag">16</span><span class="selector-pseudo">:36</span><span class="selector-pseudo">:56.842</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[4714:1552910]</span> 原信号: <span class="selector-tag">1234</span></span><br><span class="line"><span class="selector-tag">2017-01-03</span> <span class="selector-tag">16</span><span class="selector-pseudo">:36</span><span class="selector-pseudo">:56.842</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[4714:1552910]</span> 长度大于<span class="selector-tag">3</span>的信号：<span class="selector-tag">1234</span></span><br><span class="line"><span class="selector-tag">2017-01-03</span> <span class="selector-tag">16</span><span class="selector-pseudo">:36</span><span class="selector-pseudo">:58.350</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[4714:1552910]</span> 原信号: <span class="selector-tag">12345</span></span><br><span class="line"><span class="selector-tag">2017-01-03</span> <span class="selector-tag">16</span><span class="selector-pseudo">:36</span><span class="selector-pseudo">:58.351</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[4714:1552910]</span> 长度大于<span class="selector-tag">3</span>的信号：<span class="selector-tag">12345</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="ignore"><a href="#ignore" class="headerlink" title="ignore"></a>ignore</h6><ul>
<li><p><strong>作用</strong></p>
<p>  忽略某些信号.</p>
</li>
<li><p><strong>使用</strong></p>
</li>
<li><p><strong>作用</strong></p>
<p>  忽略某些值的信号.</p>
<p>  底层调用了 <code>filter</code> 与 过滤值进行比较，若相等返回则 <code>NO</code></p>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">  	<span class="comment">// 内部调用filter过滤，忽略掉字符为 @“1”的值</span></span><br><span class="line">[[_textField.rac_textSignal <span class="string">ignore:</span>@<span class="string">"1"</span>] <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line"></span><br><span class="line"> 	 NSLog(@<span class="string">"%@"</span>,x);</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="distinctUntilChanged"><a href="#distinctUntilChanged" class="headerlink" title="distinctUntilChanged"></a>distinctUntilChanged</h6><ul>
<li><p><strong>作用</strong></p>
<p>  当上一次的值和当前的值有明显的变化就会发出信号，否则会被忽略掉。</p>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight hy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[[_textField.rac_textSignal distinctUntilChanged] subscribeNext:^(<span class="name"><span class="builtin-name">id</span></span> x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"%@"</span>,x)<span class="comment">;</span></span><br><span class="line">   &#125;]<span class="comment">;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="skip"><a href="#skip" class="headerlink" title="skip"></a>skip</h6><ul>
<li><p><strong>作用</strong></p>
<p>  跳过 <strong>第N次</strong> 的发送的信号.</p>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 表示输入第一次，不会被监听到，跳过第一次发出的信号</span></span><br><span class="line"><span class="selector-attr">[[_textField.rac_textSignal skip:1]</span> <span class="selector-tag">subscribeNext</span>:^(id x) &#123;</span><br><span class="line"></span><br><span class="line">   <span class="selector-tag">NSLog</span>(@<span class="string">"%@"</span>,x);</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h5 id="take"><a href="#take" class="headerlink" title="take"></a>take</h5><ul>
<li><p><strong>作用</strong></p>
<p>  取 <strong>前N次</strong> 的发送的信号.</p>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight prolog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="symbol">RACSubject</span> *subject = [<span class="symbol">RACSubject</span> subject] ;</span><br><span class="line">   </span><br><span class="line">   // 取 前两次 发送的信号</span><br><span class="line">   [[subject take:<span class="number">2</span>] subscribeNext:^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       <span class="symbol">NSLog</span>(@<span class="string">"%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   [subject sendNext:@<span class="number">1</span>];</span><br><span class="line">   [subject sendNext:@<span class="number">2</span>];</span><br><span class="line">   [subject sendNext:@<span class="number">3</span>];</span><br><span class="line">   </span><br><span class="line">   // 输出</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">17</span>:<span class="number">35</span>:<span class="number">54.566</span> <span class="symbol">ReactiveCocoa</span>进阶[<span class="number">4969</span>:<span class="number">1677908</span>] <span class="number">1</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-03</span> <span class="number">17</span>:<span class="number">35</span>:<span class="number">54.567</span> <span class="symbol">ReactiveCocoa</span>进阶[<span class="number">4969</span>:<span class="number">1677908</span>] <span class="number">2</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="takeLast"><a href="#takeLast" class="headerlink" title="takeLast"></a>takeLast</h6><ul>
<li><p><strong>作用</strong></p>
<p>  取 <strong>最后N次</strong> 的发送的信号</p>
<p>  前提条件，订阅者必须调用完成 <code>sendCompleted</code>，因为只有完成，就知道总共有多少信号.</p>
</li>
<li><p><strong>使用</strong>    </p>
  <figure class="highlight armasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="symbol">RACSubject</span> *<span class="keyword">subject </span>= [RACSubject <span class="keyword">subject] </span><span class="comment">;</span></span><br><span class="line">   </span><br><span class="line">   // 取 后两次 发送的信号</span><br><span class="line">   [[<span class="keyword">subject </span>takeLast:<span class="number">2</span>] <span class="keyword">subscribeNext:^(id </span>x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(<span class="comment">@"%@", x);</span></span><br><span class="line">   &#125;]<span class="comment">;</span></span><br><span class="line">   </span><br><span class="line">   [<span class="keyword">subject </span>sendNext:<span class="comment">@1];</span></span><br><span class="line">   [<span class="keyword">subject </span>sendNext:<span class="comment">@2];</span></span><br><span class="line">   [<span class="keyword">subject </span>sendNext:<span class="comment">@3];</span></span><br><span class="line">   </span><br><span class="line">   // 必须 跳用完成</span><br><span class="line">   [<span class="keyword">subject </span>sendCompleted]<span class="comment">;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="takeUntil"><a href="#takeUntil" class="headerlink" title="takeUntil"></a>takeUntil</h6><ul>
<li><p><strong>作用</strong></p>
<p>  获取信号直到某个信号执行完成</p>
</li>
<li><p><strong>使用</strong>    </p>
  <figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">	<span class="comment">// 监听文本框的改变直到当前对象被销毁</span></span><br><span class="line">[<span class="meta">_textField.rac_textSignal takeUntil:self.rac_willDeallocSignal</span>];</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="switchToLatest"><a href="#switchToLatest" class="headerlink" title="switchToLatest"></a>switchToLatest</h6><ul>
<li><p><strong>作用</strong></p>
<p>  用于signalOfSignals（信号的信号），有时候信号也会发出信号，会在signalOfSignals中，获取signalOfSignals发送的最新信号。</p>
</li>
<li><p><strong>注意</strong></p>
<p>  switchToLatest：只能用于信号中的信号</p>
</li>
<li><p><strong>使用</strong>    </p>
  <figure class="highlight prolog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="symbol">RACSubject</span> *signalOfSignals = [<span class="symbol">RACSubject</span> subject];</span><br><span class="line">   <span class="symbol">RACSubject</span> *signal = [<span class="symbol">RACSubject</span> subject];</span><br><span class="line">   </span><br><span class="line">   // 获取信号中信号最近发出信号，订阅最近发出的信号。</span><br><span class="line">   [signalOfSignals.switchToLatest subscribeNext:^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       <span class="symbol">NSLog</span>(@<span class="string">"%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   [signalOfSignals sendNext:signal];</span><br><span class="line">   [signal sendNext:@<span class="number">1</span>];</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="秩序"><a href="#秩序" class="headerlink" title="秩序"></a>秩序</h4><p>秩序包括 <code>doNext</code> 和 <code>doCompleted</code> 这两个方法，主要是在 执行<code>sendNext</code> 或者 <code>sendCompleted</code>之前，先执行这些方法中Block。</p>
<h6 id="doNext"><a href="#doNext" class="headerlink" title="doNext"></a>doNext</h6><p>执行<code>sendNext</code>之前，会先执行这个<code>doNext</code>的 Block</p>
<h6 id="doCompleted"><a href="#doCompleted" class="headerlink" title="doCompleted"></a>doCompleted</h6><p>执行<code>sendCompleted</code>之前，会先执行这<code>doCompleted</code>的<code>Block</code></p>
<figure class="highlight scheme"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">[[[[<span class="name">RACSignal</span> createSignal:^RACDisposable *(<span class="name">id&lt;RACSubscriber&gt;</span> subscriber) &#123;</span><br><span class="line">    </span><br><span class="line">    [<span class="name">subscriber</span> sendNext:@<span class="string">"hi"</span>]<span class="comment">;</span></span><br><span class="line">    </span><br><span class="line">    [<span class="name">subscriber</span> sendCompleted]<span class="comment">;</span></span><br><span class="line">    </span><br><span class="line">    return nil<span class="comment">;</span></span><br><span class="line">    </span><br><span class="line">&#125;] doNext:^(<span class="name">id</span> x) &#123;</span><br><span class="line">    </span><br><span class="line">    // 执行 [<span class="name">subscriber</span> sendNext:@<span class="string">"hi"</span>] 之前会调用这个 Block</span><br><span class="line">    NSLog(<span class="name">@</span><span class="string">"doNext"</span>)<span class="comment">;</span></span><br><span class="line">    </span><br><span class="line">&#125;] doCompleted:^&#123;</span><br><span class="line">    </span><br><span class="line">    // 执行 [<span class="name">subscriber</span> sendCompleted] 之前会调用这 Block</span><br><span class="line">    NSLog(<span class="name">@</span><span class="string">"doCompleted"</span>)<span class="comment">;</span></span><br><span class="line">&#125;] subscribeNext:^(<span class="name">id</span> x) &#123;</span><br><span class="line">    </span><br><span class="line">    NSLog(<span class="name">@</span><span class="string">"%@"</span>, x)<span class="comment">;</span></span><br><span class="line">&#125;]<span class="comment">;</span></span><br></pre></td></tr></table></figure>
<h4 id="线程"><a href="#线程" class="headerlink" title="线程"></a>线程</h4><p><strong>ReactiveCocoa</strong> 中的线程操作 包括 <code>deliverOn</code> 和 <code>subscribeOn</code>这两种，将 <em>传递的内容</em> 或 创建信号时 <em>block中的代码</em> 切换到指定的线程中执行。</p>
<h6 id="deliverOn"><a href="#deliverOn" class="headerlink" title="deliverOn"></a>deliverOn</h6><ul>
<li><p><strong>作用</strong></p>
<p>  内容传递切换到制定线程中，副作用在原来线程中,把在创建信号时block中的代码称之为副作用。</p>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">	<span class="comment">// 在子线程中执行</span></span><br><span class="line">	<span class="built_in">dispatch_async</span>(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>), ^&#123;</span><br><span class="line">        </span><br><span class="line">        [[[RACSignal createSignal:^RACDisposable *(<span class="keyword">id</span>&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">        </span><br><span class="line">            <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</span><br><span class="line">            </span><br><span class="line">            [subscriber sendNext:@<span class="number">123</span>];</span><br><span class="line">            </span><br><span class="line">            [subscriber sendCompleted];</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">return</span> <span class="literal">nil</span>;</span><br><span class="line">        &#125;]</span><br><span class="line">          deliverOn:[RACScheduler mainThreadScheduler]]</span><br><span class="line">          </span><br><span class="line">         subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">         </span><br><span class="line">             <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, x);</span><br><span class="line">             </span><br><span class="line">             <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</span><br><span class="line">         &#125;];</span><br><span class="line">    &#125;);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 输出</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">10</span>:<span class="number">35</span>:<span class="number">55.415</span> ReactiveCocoa进阶[<span class="number">1183</span>:<span class="number">224535</span>] &lt;<span class="built_in">NSThread</span>: <span class="number">0x608000270f00</span>&gt;&#123;number = <span class="number">3</span>, name = (null)&#125;</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">10</span>:<span class="number">35</span>:<span class="number">55.415</span> ReactiveCocoa进阶[<span class="number">1183</span>:<span class="number">224482</span>] <span class="number">123</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">10</span>:<span class="number">35</span>:<span class="number">55.415</span> ReactiveCocoa进阶[<span class="number">1183</span>:<span class="number">224482</span>] &lt;<span class="built_in">NSThread</span>: <span class="number">0x600000079bc0</span>&gt;&#123;number = <span class="number">1</span>, name = main&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<pre><code>可以看到`副作用`在 *子线程* 中执行，而 `传递的内容` 在 *主线程* 中接收
</code></pre><h6 id="subscribeOn"><a href="#subscribeOn" class="headerlink" title="subscribeOn"></a>subscribeOn</h6><ul>
<li><p><strong>作用</strong></p>
<p>  <strong>subscribeOn</strong>则是将 <code>内容传递</code> 和 <code>副作用</code> 都会切换到指定线程中</p>
</li>
<li><p><strong>使用</strong></p>
  <figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">    <span class="built_in">dispatch_async</span>(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="number">0</span>), ^&#123;</span><br><span class="line">        </span><br><span class="line">        [[[RACSignal createSignal:^RACDisposable *(<span class="keyword">id</span>&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">        </span><br><span class="line">            <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</span><br><span class="line">            </span><br><span class="line">            [subscriber sendNext:@<span class="number">123</span>];</span><br><span class="line">            </span><br><span class="line">            [subscriber sendCompleted];</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">return</span> <span class="literal">nil</span>;</span><br><span class="line">        &#125;]</span><br><span class="line">          subscribeOn:[RACScheduler mainThreadScheduler]] <span class="comment">//传递的内容到主线程中</span></span><br><span class="line">         subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">         </span><br><span class="line">             <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, x);</span><br><span class="line">             </span><br><span class="line">             <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, [<span class="built_in">NSThread</span> currentThread]);</span><br><span class="line">         &#125;];</span><br><span class="line">    &#125;);	</span><br><span class="line">	<span class="comment">//</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">10</span>:<span class="number">44</span>:<span class="number">47.558</span> ReactiveCocoa进阶[<span class="number">1243</span>:<span class="number">275126</span>] &lt;<span class="built_in">NSThread</span>: <span class="number">0x608000077640</span>&gt;&#123;number = <span class="number">1</span>, name = main&#125;</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">10</span>:<span class="number">44</span>:<span class="number">47.558</span> ReactiveCocoa进阶[<span class="number">1243</span>:<span class="number">275126</span>] <span class="number">123</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">10</span>:<span class="number">44</span>:<span class="number">47.558</span> ReactiveCocoa进阶[<span class="number">1243</span>:<span class="number">275126</span>] &lt;<span class="built_in">NSThread</span>: <span class="number">0x608000077640</span>&gt;&#123;number = <span class="number">1</span>, name = main&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<pre><code>`内容传递` 和 `副作用` 都切换到了 *主线程* 执行
</code></pre><h4 id="时间"><a href="#时间" class="headerlink" title="时间"></a>时间</h4><p>时间操作就会设置信号超时，定时和延时。</p>
<h6 id="interval-定时"><a href="#interval-定时" class="headerlink" title="interval 定时"></a>interval 定时</h6><ul>
<li><p><strong>作用</strong></p>
<p>  定时：每隔一段时间发出信号</p>
  <figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 每隔1秒发送信号，指定当前线程执行</span></span><br><span class="line"><span class="selector-attr">[[RACSignal interval:1 onScheduler:[RACScheduler currentScheduler]</span>] <span class="selector-tag">subscribeNext</span>:^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       <span class="selector-tag">NSLog</span>(@<span class="string">"定时:%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line"><span class="comment">// 输出</span></span><br><span class="line"><span class="selector-tag">2017-01-04</span> <span class="selector-tag">13</span><span class="selector-pseudo">:48</span><span class="selector-pseudo">:55.196</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[1980:492724]</span> 定时<span class="selector-pseudo">:2017-01-04</span> <span class="selector-tag">05</span><span class="selector-pseudo">:48</span><span class="selector-pseudo">:55</span> +<span class="selector-tag">0000</span></span><br><span class="line"><span class="selector-tag">2017-01-04</span> <span class="selector-tag">13</span><span class="selector-pseudo">:48</span><span class="selector-pseudo">:56.195</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[1980:492724]</span> 定时<span class="selector-pseudo">:2017-01-04</span> <span class="selector-tag">05</span><span class="selector-pseudo">:48</span><span class="selector-pseudo">:56</span> +<span class="selector-tag">0000</span></span><br><span class="line"><span class="selector-tag">2017-01-04</span> <span class="selector-tag">13</span><span class="selector-pseudo">:48</span><span class="selector-pseudo">:57.196</span> <span class="selector-tag">ReactiveCocoa</span>进阶<span class="selector-attr">[1980:492724]</span> 定时<span class="selector-pseudo">:2017-01-04</span> <span class="selector-tag">05</span><span class="selector-pseudo">:48</span><span class="selector-pseudo">:57</span> +<span class="selector-tag">0000</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="timeout-超时"><a href="#timeout-超时" class="headerlink" title="timeout 超时"></a>timeout 超时</h6><ul>
<li><p><strong>作用</strong></p>
<p>  超时，可以让一个信号在一定的时间后，自动报错。</p>
  <figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">RACSignal *signal = [[RACSignal createSignal:^RACDisposable *(<span class="keyword">id</span>&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       <span class="comment">// 不发送信号，模拟超时状态</span></span><br><span class="line">       <span class="comment">// [subscriber sendNext:@"hello"];</span></span><br><span class="line">       <span class="comment">//[subscriber sendCompleted];</span></span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> <span class="literal">nil</span>;</span><br><span class="line">   &#125;] timeout:<span class="number">1</span> onScheduler:[RACScheduler currentScheduler]];<span class="comment">// 设置1秒超时</span></span><br><span class="line">   </span><br><span class="line">   [signal subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">       </span><br><span class="line">       <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, x);</span><br><span class="line">   &#125; error:^(<span class="built_in">NSError</span> *error) &#123;</span><br><span class="line">       </span><br><span class="line">       <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, error);</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 执行代码 1秒后 输出：</span></span><br><span class="line">   <span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">13</span>:<span class="number">48</span>:<span class="number">55.195</span> ReactiveCocoa进阶[<span class="number">1980</span>:<span class="number">492724</span>] Error Domain=RACSignalErrorDomain Code=<span class="number">1</span> <span class="string">"(null)"</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="delay-延时"><a href="#delay-延时" class="headerlink" title="delay 延时"></a>delay 延时</h6><ul>
<li><p><strong>作用</strong></p>
<p>  延时，延迟一段时间后发送信号</p>
  <figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">RACSignal *signal2 = [[[RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">       </span><br><span class="line">       [subscriber <span class="string">sendNext:</span>@<span class="string">"延迟输出"</span>];</span><br><span class="line">       </span><br><span class="line">       <span class="keyword">return</span> nil;</span><br><span class="line">   &#125;] <span class="string">delay:</span><span class="number">2</span>] <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 执行代码 2秒后 输出</span></span><br><span class="line">   <span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">13</span>:<span class="number">55</span>:<span class="number">23.751</span> ReactiveCocoa进阶[<span class="number">2030</span>:<span class="number">525038</span>] 延迟输出</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="重复"><a href="#重复" class="headerlink" title="重复"></a>重复</h4><h6 id="retry"><a href="#retry" class="headerlink" title="retry"></a>retry</h6><ul>
<li><p><strong>作用</strong></p>
<p>  重试：只要 发送错误 <code>sendError:</code>,就会 重新执行 创建信号的Block 直到成功</p>
  <figure class="highlight dns"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">	__block int i = <span class="number">0</span><span class="comment">;</span></span><br><span class="line">    </span><br><span class="line">    [[[RACSignal createSignal:^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">        </span><br><span class="line">        if (i == <span class="number">5</span>) &#123;</span><br><span class="line">            </span><br><span class="line">            [subscriber sendNext:@"Hello"]<span class="comment">;</span></span><br><span class="line">            </span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            </span><br><span class="line">            // 发送错误</span><br><span class="line">            NSLog(@"收到错误:%d", i)<span class="comment">;</span></span><br><span class="line">            [subscriber sendError:nil]<span class="comment">;</span></span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        i++<span class="comment">;</span></span><br><span class="line">        </span><br><span class="line">        return nil<span class="comment">;</span></span><br><span class="line">        </span><br><span class="line">    &#125;] retry] subscribeNext:^(id x) &#123;</span><br><span class="line">        </span><br><span class="line">        NSLog(@"%@", x)<span class="comment">;</span></span><br><span class="line">        </span><br><span class="line">    &#125; error:^(NSError *error) &#123;</span><br><span class="line">        </span><br><span class="line">        NSLog(@"%@", error)<span class="comment">;</span></span><br><span class="line">        </span><br><span class="line">    &#125;]<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">	// 输出</span><br><span class="line"><span class="number">2017-01-04</span> <span class="number">14</span>:<span class="number">36:51.594</span> ReactiveCocoa进阶[<span class="number">2443:667226</span>] 收到错误信息:<span class="number">0</span></span><br><span class="line"><span class="number">2017-01-04</span> <span class="number">14</span>:<span class="number">36:51.595</span> ReactiveCocoa进阶[<span class="number">2443:667226</span>] 收到错误信息:<span class="number">1</span></span><br><span class="line"><span class="number">2017-01-04</span> <span class="number">14</span>:<span class="number">36:51.595</span> ReactiveCocoa进阶[<span class="number">2443:667226</span>] 收到错误信息:<span class="number">2</span></span><br><span class="line"><span class="number">2017-01-04</span> <span class="number">14</span>:<span class="number">36:51.596</span> ReactiveCocoa进阶[<span class="number">2443:667226</span>] 收到错误信息:<span class="number">3</span></span><br><span class="line"><span class="number">2017-01-04</span> <span class="number">14</span>:<span class="number">36:51.596</span> ReactiveCocoa进阶[<span class="number">2443:667226</span>] 收到错误信息:<span class="number">4</span></span><br><span class="line"><span class="number">2017-01-04</span> <span class="number">14</span>:<span class="number">36:51.596</span> ReactiveCocoa进阶[<span class="number">2443:667226</span>] Hello</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="replay"><a href="#replay" class="headerlink" title="replay"></a>replay</h6><ul>
<li><p><strong>作用</strong></p>
<p>  重放：当一个信号被多次订阅,反复播放内容</p>
  <figure class="highlight prolog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">	<span class="symbol">RACSignal</span> *signal = [[<span class="symbol">RACSignal</span> createSignal:^<span class="symbol">RACDisposable</span> *(id&lt;<span class="symbol">RACSubscriber</span>&gt; subscriber) &#123;</span><br><span class="line">        </span><br><span class="line">        [subscriber sendNext:@<span class="number">1</span>];</span><br><span class="line">        [subscriber sendNext:@<span class="number">2</span>];</span><br><span class="line">        </span><br><span class="line">        return nil;</span><br><span class="line">    &#125;] replay];</span><br><span class="line">    </span><br><span class="line">    [signal subscribeNext:^(id x) &#123;</span><br><span class="line">        <span class="symbol">NSLog</span>(@<span class="string">"%@"</span>, x);</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">    [signal subscribeNext:^(id x) &#123;</span><br><span class="line">        <span class="symbol">NSLog</span>(@<span class="string">"%@"</span>, x);</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">    // 输出</span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">14</span>:<span class="number">51</span>:<span class="number">01.934</span> <span class="symbol">ReactiveCocoa</span>进阶[<span class="number">2544</span>:<span class="number">706740</span>] <span class="number">1</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">14</span>:<span class="number">51</span>:<span class="number">01.934</span> <span class="symbol">ReactiveCocoa</span>进阶[<span class="number">2544</span>:<span class="number">706740</span>] <span class="number">2</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">14</span>:<span class="number">51</span>:<span class="number">01.934</span> <span class="symbol">ReactiveCocoa</span>进阶[<span class="number">2544</span>:<span class="number">706740</span>] <span class="number">1</span></span><br><span class="line"><span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">14</span>:<span class="number">51</span>:<span class="number">01.935</span> <span class="symbol">ReactiveCocoa</span>进阶[<span class="number">2544</span>:<span class="number">706740</span>] <span class="number">2</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h6 id="throttle"><a href="#throttle" class="headerlink" title="throttle"></a>throttle</h6><ul>
<li><p><strong>作用</strong></p>
<p>  节流:当某个信号发送比较频繁时，可以使用节流，在某一段时间不发送信号内容，过了一段时间获取信号的最新内容发出。</p>
  <figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">RACSubject *subject = [RACSubject subject];</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 节流1秒，1秒后接收最后一个发送的信号</span></span><br><span class="line">   [[subject <span class="string">throttle:</span><span class="number">1</span>] <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">       </span><br><span class="line">       NSLog(@<span class="string">"%@"</span>, x);</span><br><span class="line">   &#125;];</span><br><span class="line">   </span><br><span class="line">   [subject <span class="string">sendNext:</span>@<span class="number">1</span>];</span><br><span class="line">   [subject <span class="string">sendNext:</span>@<span class="number">2</span>];</span><br><span class="line">   [subject <span class="string">sendNext:</span>@<span class="number">3</span>];</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 输出</span></span><br><span class="line">   <span class="number">2017</span><span class="number">-01</span><span class="number">-04</span> <span class="number">15</span>:<span class="number">02</span>:<span class="number">37.543</span> ReactiveCocoa进阶[<span class="number">2731</span>:<span class="number">758193</span>] <span class="number">3</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="MVVM架构思想"><a href="#MVVM架构思想" class="headerlink" title="MVVM架构思想"></a>MVVM架构思想</h1><hr>
<p>程序为什么要有架构？便于程序开发与维护.</p>
<h4 id="常见的架构"><a href="#常见的架构" class="headerlink" title="常见的架构"></a>常见的架构</h4><ul>
<li><p><strong>MVC</strong></p>
<p>  M:模型 V:视图 C:控制器</p>
</li>
<li><p><strong>MVVM</strong></p>
<p>  M:模型 V:视图+控制器 VM:视图模型</p>
</li>
<li><p><strong>MVCS</strong></p>
<p>   M:模型 V:视图 C:控制器 C:服务类</p>
</li>
<li><p><a href="http://www.cocoachina.com/ios/20140703/9016.html" target="_blank" rel="noopener"><strong>VIPER</strong></a></p>
<p>  V:视图 I:交互器 P:展示器 E:实体 R:路由</p>
</li>
</ul>
<h4 id="MVVM介绍"><a href="#MVVM介绍" class="headerlink" title="MVVM介绍"></a>MVVM介绍</h4><ul>
<li><p>模型(M):保存视图数据。</p>
</li>
<li><p>视图+控制器(V):展示内容 + 如何展示</p>
</li>
<li><p>视图模型(VM):处理展示的业务逻辑，包括按钮的点击，数据的请求和解析等等。</p>
</li>
</ul>
<h1 id="实战一：登录界面"><a href="#实战一：登录界面" class="headerlink" title="实战一：登录界面"></a>实战一：登录界面</h1><h4 id="需求"><a href="#需求" class="headerlink" title="需求"></a>需求</h4><ol>
<li>监听两个文本框的内容</li>
<li>有内容登录按键才允许按钮点击</li>
<li>返回登录结果</li>
</ol>
<h4 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h4><ol>
<li>界面的所有业务逻辑都交给控制器做处理</li>
<li>在MVVM架构中把控制器的业务全部搬去VM模型，也就是每个控制器对应一个VM模型.</li>
</ol>
<h4 id="步骤"><a href="#步骤" class="headerlink" title="步骤"></a>步骤</h4><ol>
<li>创建LoginViewModel类，处理登录界面业务逻辑.</li>
<li>这个类里面应该保存着账号的信息，创建一个账号Account模型</li>
<li>LoginViewModel应该保存着账号信息Account模型。</li>
<li>需要时刻监听Account模型中的账号和密码的改变，怎么监听？</li>
<li>在非RAC开发中，都是习惯赋值，在RAC开发中，需要改变开发思维，由赋值转变为绑定，可以在一开始初始化的时候，就给Account模型中的属性绑定，并不需要重写set方法。</li>
<li>每次Account模型的值改变，就需要判断按钮能否点击，在VM模型中做处理，给外界提供一个能否点击按钮的信号.</li>
<li>这个登录信号需要判断Account中账号和密码是否有值，用KVO监听这两个值的改变，把他们聚合成登录信号.</li>
<li>监听按钮的点击，由VM处理，应该给VM声明一个RACCommand，专门处理登录业务逻辑.</li>
<li>执行命令，把数据包装成信号传递出去</li>
<li>监听命令中信号的数据传递</li>
<li>监听命令的执行时刻</li>
</ol>
<h4 id="运行效果"><a href="#运行效果" class="headerlink" title="运行效果"></a>运行效果</h4><p><img src="https://ww3.sinaimg.cn/large/006y8lVagw1fbgvoh8yu6j30bj0l43yz.jpg" alt="登录界面"></p>
<h4 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h4><p><code>MyViewController.m</code></p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#import <span class="meta-string">"MyViewController.h"</span></span></span><br><span class="line"><span class="meta">#import <span class="meta-string">"LoginViewModel.h"</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">MyViewController</span> ()</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">strong</span>) LoginViewModel *loginViewModel;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">weak</span>, <span class="keyword">nonatomic</span>) <span class="keyword">IBOutlet</span> <span class="built_in">UITextField</span> *accountField;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">weak</span>, <span class="keyword">nonatomic</span>) <span class="keyword">IBOutlet</span> <span class="built_in">UITextField</span> *pwdField;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">weak</span>, <span class="keyword">nonatomic</span>) <span class="keyword">IBOutlet</span> <span class="built_in">UIButton</span> *loginBtn;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">MyViewController</span></span></span><br><span class="line"></span><br><span class="line">- (<span class="keyword">void</span>)viewDidLoad &#123;</span><br><span class="line">    [<span class="keyword">super</span> viewDidLoad];</span><br><span class="line">    </span><br><span class="line">    [<span class="keyword">self</span> bindModel];</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="keyword">void</span>)didReceiveMemoryWarning &#123;</span><br><span class="line">    [<span class="keyword">super</span> didReceiveMemoryWarning];</span><br><span class="line">    <span class="comment">// Dispose of any resources that can be recreated.</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 视图模型绑定</span></span><br><span class="line">- (<span class="keyword">void</span>)bindModel &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 给模型的属性绑定信号</span></span><br><span class="line">    <span class="comment">//</span></span><br><span class="line">    RAC(<span class="keyword">self</span>.loginViewModel.account, account) = _accountField.rac_textSignal;</span><br><span class="line">    RAC(<span class="keyword">self</span>.loginViewModel.account, pwd) = _pwdField.rac_textSignal;</span><br><span class="line">    </span><br><span class="line">    RAC(<span class="keyword">self</span>.loginBtn, enabled) = <span class="keyword">self</span>.loginViewModel.enableLoginSignal;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 监听登录点击</span></span><br><span class="line">    [[_loginBtn rac_signalForControlEvents:<span class="built_in">UIControlEventTouchUpInside</span>] subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">        </span><br><span class="line">        [<span class="keyword">self</span>.loginViewModel.LoginCommand execute:<span class="literal">nil</span>];</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line">- (<span class="keyword">IBAction</span>)btnTap:(<span class="keyword">id</span>)sender &#123;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">#pragma mark - lazyLoad</span></span><br><span class="line"></span><br><span class="line">- (LoginViewModel *)loginViewModel &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (<span class="literal">nil</span> == _loginViewModel) &#123;</span><br><span class="line">        _loginViewModel = [[LoginViewModel alloc] init];</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> _loginViewModel;</span><br><span class="line">&#125;</span><br><span class="line">```	</span><br><span class="line">		</span><br><span class="line">`LoginViewModel.h`</span><br></pre></td></tr></table></figure>
<p>#import &lt;UIKit/UIKit.h&gt;</p>
<p>@interface Account : NSObject</p>
<p>@property (nonatomic, strong) NSString <em>account;<br>@property (nonatomic, strong) NSString </em>pwd;</p>
<p>@end</p>
<p>@interface LoginViewModel : UIViewController</p>
<p>@property (nonatomic, strong) Account *account;</p>
<p>// 是否允许登录的信号<br>@property (nonatomic, strong, readonly) RACSignal *enableLoginSignal;</p>
<p>@property (nonatomic, strong, readonly) RACCommand *LoginCommand;</p>
<p>@end</p>
<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">`LoginViewModel.m`</span><br></pre></td></tr></table></figure>
<p>#import “LoginViewModel.h”</p>
<p>@implementation Account</p>
<p>@end</p>
<p>@interface LoginViewModel ()</p>
<p>@end</p>
<p>@implementation LoginViewModel</p>
<ul>
<li><p>(instancetype)init {</p>
<p>  if (self = [super init]) {</p>
<pre><code>[self initialBind];
</code></pre><p>  }<br>  return self;<br>}</p>
</li>
<li><p>(void)initialBind {</p>
<p>  // 监听账号属性改变， 把他们合成一个信号<br>  _enableLoginSignal = [RACSubject combineLatest:@[RACObserve(self.account, account), RACObserve(self.account, pwd)] reduce:^id(NSString <em>accout, NSString </em>pwd){</p>
<pre><code>return @(accout.length &amp;&amp; pwd.length);
</code></pre><p>  }];</p>
<p>  // 处理业务逻辑<br>  _LoginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {</p>
<pre><code>NSLog(@&quot;点击了登录&quot;);
return [RACSignal createSignal:^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) {

    // 模仿网络延迟

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        // 返回登录成功 发送成功信号
        [subscriber sendNext:@&quot;登录成功&quot;];
    });

    return nil;
}];
</code></pre><p>  }];</p>
</li>
</ul>
<pre><code>// 监听登录产生的数据
[_LoginCommand.executionSignals.switchToLatest subscribeNext:^(id x) {

    if ([x isEqualToString:@&quot;登录成功&quot;]) {
        NSLog(@&quot;登录成功&quot;);
    }

}];

[[_LoginCommand.executing skip:1] subscribeNext:^(id x) {

    if ([x isEqualToNumber:@(YES)]) {

        NSLog(@&quot;正在登陆...&quot;);
    } else {

    // 登录成功
    NSLog(@&quot;登陆成功&quot;);

    }

}];
</code></pre><p>}</p>
<p>#pragma mark - lazyLoad</p>
<ul>
<li><p>(Account *)account<br>{<br>  if (_account == nil) {</p>
<pre><code>_account = [[Account alloc] init];
</code></pre><p>  }<br>  return _account;<br>}</p>
</li>
<li><p>(void)viewDidLoad {<br>  [super viewDidLoad];</p>
</li>
</ul>
<p>}</p>
<p>@end</p>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="section"># 实战二：网络请求数据</span></span><br><span class="line"></span><br><span class="line"><span class="section">#### 需求</span></span><br><span class="line"><span class="bullet">1. </span>请求一段网络数据，将请求到的数据在<span class="code">`tableView`</span>上展示</span><br><span class="line"><span class="bullet">2. </span>该数据为豆瓣图书的搜索返回结果，URL：url:https://api.douban.com/v2/book/search?q=悟空传</span><br><span class="line"></span><br><span class="line"><span class="section">#### 分析</span></span><br><span class="line"><span class="bullet">1. </span>界面的所有业务逻辑都交给<span class="strong">**控制器**</span>做处理</span><br><span class="line"><span class="bullet">2. </span>网络请求交给<span class="strong">**MV**</span>模型处理</span><br><span class="line"></span><br><span class="line"><span class="section">#### 步骤</span></span><br><span class="line"></span><br><span class="line"><span class="bullet">1. </span>控制器提供一个视图模型（requesViewModel），处理界面的业务逻辑</span><br><span class="line"><span class="bullet">2. </span>VM提供一个命令，处理请求业务逻辑</span><br><span class="line"><span class="bullet">3. </span>在创建命令的block中，会把请求包装成一个信号，等请求成功的时候，就会把数据传递出去。</span><br><span class="line"><span class="bullet">4. </span>请求数据成功，应该把字典转换成模型，保存到视图模型中，控制器想用就直接从视图模型中获取。</span><br><span class="line"></span><br><span class="line"><span class="section">#### 其他</span></span><br><span class="line"></span><br><span class="line">网络请求与图片缓存用到了[<span class="string">AFNetworking</span>](<span class="link">https://github.com/AFNetworking/AFNetworking</span>) 和 [<span class="string">SDWebImage</span>](<span class="link">https://github.com/rs/SDWebImage</span>),自行在Pods中导入。</span><br></pre></td></tr></table></figure>
<p>platform :ios, ‘8.0’</p>
<p>target ‘ReactiveCocoa进阶’ do</p>
<p>use_frameworks!<br>pod ‘ReactiveCocoa’, ‘~&gt; 2.5’<br>pod ‘AFNetworking’<br>pod ‘SDWebImage’<br>end<br><figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">#### 运行效果</span><br><span class="line"></span><br><span class="line">![](https:<span class="comment">//ww3.sinaimg.cn/large/006y8lVagw1fbgw1xnz74j30bj0l4408.jpg)</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#### 代码</span><br><span class="line"></span><br><span class="line">`SearchViewController.m`</span><br></pre></td></tr></table></figure></p>
<p>#import “SearchViewController.h”</p>
<p>#import “RequestViewModel.h”</p>
<p>@interface SearchViewController ()<uitableviewdatasource></uitableviewdatasource></p>
<p>@property (nonatomic, strong) UITableView *tableView;</p>
<p>@property (nonatomic, strong) RequestViewModel *requesViewModel;</p>
<p>@end</p>
<p>@implementation SearchViewController</p>
<ul>
<li><p>(RequestViewModel *)requesViewModel<br>{<br>  if (_requesViewModel == nil) {</p>
<pre><code>_requesViewModel = [[RequestViewModel alloc] init];
</code></pre><p>  }<br>  return _requesViewModel;<br>}</p>
</li>
<li><p>(void)viewDidLoad {<br>  [super viewDidLoad];</p>
</li>
</ul>
<pre><code>self.tableView = [[UITableView alloc] initWithFrame:self.view.frame];

self.tableView.dataSource = self;

[self.view addSubview:self.tableView];

//
RACSignal *requesSiganl = [self.requesViewModel.reuqesCommand execute:nil];

[requesSiganl subscribeNext:^(NSArray *x) {

    self.requesViewModel.models = x;

    [self.tableView reloadData];
}];
</code></pre><p>}</p>
<ul>
<li><p>(void)didReceiveMemoryWarning {<br>  [super didReceiveMemoryWarning];<br>  // Dispose of any resources that can be recreated.<br>}</p>
</li>
<li><p>(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section<br>{<br>  return self.requesViewModel.models.count;<br>}</p>
</li>
<li><p>(UITableViewCell <em>)tableView:(UITableView </em>)tableView cellForRowAtIndexPath:(NSIndexPath <em>)indexPath<br>{<br>  static NSString </em>ID = @”cell”;<br>  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];<br>  if (cell == nil) {</p>
<pre><code>cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
</code></pre><p>  }</p>
<p>  Book *book = self.requesViewModel.models[indexPath.row];<br>  cell.detailTextLabel.text = book.subtitle;<br>  cell.textLabel.text = book.title;</p>
<p>  [cell.imageView sd_setImageWithURL:[NSURL URLWithString:book.image] placeholderImage:[UIImage imageNamed:@”cellImage”]];</p>
</li>
</ul>
<pre><code>return cell;
</code></pre><p>}<br>@end<br><figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">`RequestViewModel.h`</span><br></pre></td></tr></table></figure></p>
<p>#import &lt;Foundation/Foundation.h&gt;</p>
<p>@interface Book : NSObject</p>
<p>@property (nonatomic, copy) NSString <em>subtitle;<br>@property (nonatomic, copy) NSString </em>title;<br>@property (nonatomic, copy) NSString *image;</p>
<p>@end</p>
<p>@interface RequestViewModel : NSObject</p>
<p>// 请求命令<br>@property (nonatomic, strong, readonly) RACCommand *reuqesCommand;</p>
<p>//模型数组<br>@property (nonatomic, strong) NSArray *models;</p>
<p>@end<br><figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">`RequestViewModel.m`</span><br></pre></td></tr></table></figure></p>
<p>#import “RequestViewModel.h”</p>
<p>@implementation Book</p>
<ul>
<li><p>(instancetype)initWithValue:(NSDictionary *)value {</p>
<p>  if (self = [super init]) {</p>
<pre><code>self.title = value[@&quot;title&quot;];
self.subtitle = value[@&quot;subtitle&quot;];
self.image = value[@&quot;image&quot;];
</code></pre><p>  }<br>  return self;<br>}</p>
</li>
</ul>
<ul>
<li><p>(Book <em>)bookWithDict:(NSDictionary </em>)value {</p>
<p>  return [[self alloc] initWithValue:value];<br>}</p>
</li>
</ul>
<p>@end</p>
<p>@implementation RequestViewModel</p>
<ul>
<li><p>(instancetype)init<br>{<br>  if (self = [super init]) {</p>
<pre><code>[self initialBind];
</code></pre><p>  }<br>  return self;<br>}</p>
</li>
</ul>
<ul>
<li><p>(void)initialBind<br>{<br>  _reuqesCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {</p>
<pre><code>RACSignal *requestSiganl = [RACSignal createSignal:^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) {

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@&quot;q&quot;] = @&quot;悟空传&quot;;

    //
    [[AFHTTPSessionManager manager] GET:@&quot;https://api.douban.com/v2/book/search&quot; parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {

        NSLog(@&quot;downloadProgress: %@&quot;, downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        // 数据请求成功就讲数据发送出去
        NSLog(@&quot;responseObject:%@&quot;, responseObject);

        [subscriber sendNext:responseObject];

        [subscriber sendCompleted];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@&quot;error: %@&quot;, error);
    }];
</code></pre></li>
</ul>
<pre><code>     return nil;
  }];

    // 在返回数据信号时，把数据中的字典映射成模型信号，传递出去
    return [requestSiganl map:^id(NSDictionary *value) {

        NSMutableArray *dictArr = value[@&quot;books&quot;];

        NSArray *modelArr = [[dictArr.rac_sequence map:^id(id value) {

            return [Book bookWithDict:value];

        }] array];

        return modelArr;

    }];

}];
</code></pre><p>}</p>
<p>@end</p>
<p><code>`</code></p>
<blockquote>
<p>最后附上GitHub：<a href="https://github.com/qiubaiying/ReactiveCocoa_Demo" target="_blank" rel="noopener">https://github.com/qiubaiying/ReactiveCocoa_Demo</a></p>
</blockquote>

      
    </div>
    
    
    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <!--<a href="/tags/xcode/" rel="tag"># xcode</a>-->
            <a href="/tags/xcode/" rel="tag"><i class="fa fa-tag"></i> xcode</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/12/26/2016-12-26-ReactiveCocoa-基础/" rel="next" title="ReactiveCocoa 基础">
                <i class="fa fa-chevron-left"></i> ReactiveCocoa 基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/02/04/2016-10-26-BYPhoneNumTF/" rel="prev" title="BYPhoneNumTF">
                BYPhoneNumTF <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/ichgo.jpg"
                alt="廖壬" />
            
              <p class="site-author-name" itemprop="name">廖壬</p>
              <p class="site-description motion-element" itemprop="description">Learn to choose, to forsake, to endure loneliness, to resist temptation.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">391</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">56</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/liaoren512" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:liaoren512@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5281757990/profile?rightmod=1&wvr=6&mod=personinfo" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-globe"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com" target="_blank" title="Zhihu">
                      
                        <i class="fa fa-fw fa-globe"></i>Zhihu</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常见操作方法介绍"><span class="nav-number">2.</span> <span class="nav-text">常见操作方法介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#操作须知"><span class="nav-number">2.0.0.1.</span> <span class="nav-text">操作须知</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#操作思想"><span class="nav-number">2.0.0.2.</span> <span class="nav-text">操作思想</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#操作方法"><span class="nav-number">2.0.0.3.</span> <span class="nav-text">操作方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#bind（绑定）-ReactiveCocoa核心方法"><span class="nav-number">2.0.0.4.</span> <span class="nav-text">bind（绑定）- ReactiveCocoa核心方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#映射"><span class="nav-number">2.0.0.5.</span> <span class="nav-text">映射</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#flattenMap"><span class="nav-number">2.0.0.5.0.1.</span> <span class="nav-text">flattenMap</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#Map"><span class="nav-number">2.0.0.5.0.2.</span> <span class="nav-text">Map</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#FlatternMap-和-Map-的区别"><span class="nav-number">2.0.0.5.0.3.</span> <span class="nav-text">FlatternMap 和 Map 的区别</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#组合"><span class="nav-number">2.0.0.6.</span> <span class="nav-text">组合</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#concat"><span class="nav-number">2.0.0.6.0.1.</span> <span class="nav-text">concat</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#then"><span class="nav-number">2.0.0.6.0.2.</span> <span class="nav-text">then</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#merge"><span class="nav-number">2.0.0.6.0.3.</span> <span class="nav-text">merge</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#zip"><span class="nav-number">2.0.0.6.0.4.</span> <span class="nav-text">zip</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#combineLatest"><span class="nav-number">2.0.0.6.0.5.</span> <span class="nav-text">combineLatest</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#reduce"><span class="nav-number">2.0.0.6.0.6.</span> <span class="nav-text">reduce</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#过滤"><span class="nav-number">2.0.0.7.</span> <span class="nav-text">过滤</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#filter"><span class="nav-number">2.0.0.7.0.1.</span> <span class="nav-text">filter</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#ignore"><span class="nav-number">2.0.0.7.0.2.</span> <span class="nav-text">ignore</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#distinctUntilChanged"><span class="nav-number">2.0.0.7.0.3.</span> <span class="nav-text">distinctUntilChanged</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#skip"><span class="nav-number">2.0.0.7.0.4.</span> <span class="nav-text">skip</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#take"><span class="nav-number">2.0.0.7.1.</span> <span class="nav-text">take</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#takeLast"><span class="nav-number">2.0.0.7.1.1.</span> <span class="nav-text">takeLast</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#takeUntil"><span class="nav-number">2.0.0.7.1.2.</span> <span class="nav-text">takeUntil</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#switchToLatest"><span class="nav-number">2.0.0.7.1.3.</span> <span class="nav-text">switchToLatest</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#秩序"><span class="nav-number">2.0.0.8.</span> <span class="nav-text">秩序</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#doNext"><span class="nav-number">2.0.0.8.0.1.</span> <span class="nav-text">doNext</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#doCompleted"><span class="nav-number">2.0.0.8.0.2.</span> <span class="nav-text">doCompleted</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#线程"><span class="nav-number">2.0.0.9.</span> <span class="nav-text">线程</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#deliverOn"><span class="nav-number">2.0.0.9.0.1.</span> <span class="nav-text">deliverOn</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#subscribeOn"><span class="nav-number">2.0.0.9.0.2.</span> <span class="nav-text">subscribeOn</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#时间"><span class="nav-number">2.0.0.10.</span> <span class="nav-text">时间</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#interval-定时"><span class="nav-number">2.0.0.10.0.1.</span> <span class="nav-text">interval 定时</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#timeout-超时"><span class="nav-number">2.0.0.10.0.2.</span> <span class="nav-text">timeout 超时</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#delay-延时"><span class="nav-number">2.0.0.10.0.3.</span> <span class="nav-text">delay 延时</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#重复"><span class="nav-number">2.0.0.11.</span> <span class="nav-text">重复</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#retry"><span class="nav-number">2.0.0.11.0.1.</span> <span class="nav-text">retry</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#replay"><span class="nav-number">2.0.0.11.0.2.</span> <span class="nav-text">replay</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#throttle"><span class="nav-number">2.0.0.11.0.3.</span> <span class="nav-text">throttle</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#MVVM架构思想"><span class="nav-number">3.</span> <span class="nav-text">MVVM架构思想</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#常见的架构"><span class="nav-number">3.0.0.1.</span> <span class="nav-text">常见的架构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#MVVM介绍"><span class="nav-number">3.0.0.2.</span> <span class="nav-text">MVVM介绍</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#实战一：登录界面"><span class="nav-number">4.</span> <span class="nav-text">实战一：登录界面</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#需求"><span class="nav-number">4.0.0.1.</span> <span class="nav-text">需求</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#分析"><span class="nav-number">4.0.0.2.</span> <span class="nav-text">分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#步骤"><span class="nav-number">4.0.0.3.</span> <span class="nav-text">步骤</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#运行效果"><span class="nav-number">4.0.0.4.</span> <span class="nav-text">运行效果</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#代码"><span class="nav-number">4.0.0.5.</span> <span class="nav-text">代码</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<!--<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>-->

<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">廖壬</span>

  
</div>

<!-- 在网站底部加上访问量-->
<!--<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_pv"></span>
</span>
</div>-->
<!--pv的方式，单个用户连续点击n篇文章，记录n次访问量-->
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>



-->
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共字</span>
</div>
        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>